<template>
  <div class="pub-empty-car">
    <el-dialog
      v-el-drag-dialog="{ drag: true, full: false, resize: false }"
      :visible="true"
      :close-on-click-modal="false"
      @close="closeMd"
      :title="`发布空车`"
      width="400px">
      <el-form 
        :model="fm.ps" 
        :ref="fm.fname"
        @keyup.enter.native="onSubmit" 
        :label-width="'100px'">
        <el-form-item 
          label="出发地点" 
          prop="spoint.name"
          :rules="[{ required: true, message: '请选择开始地点', trigger: 'bulr' }]">
          <MapPointInp 
            v-if="stationList.length > 0"
            :name="'spoint'" 
            :pindex="0" 
            :placeholder="'开始地点'" 
            :defList="stationList"
            :point="fm.ps.epoint"
            :defPoint="fm.ps.spoint"
            @handleSel="setPoint"
            style="width: 265px;"/>
        </el-form-item>

        <el-form-item 
          label="到达地点"
          prop="epoint.name"
          :rules="[{ required: true, message: '请选择结束地点', trigger: 'blur' }]">
          <MapPointInp 
            v-if="stationList.length > 0"
            :name="'epoint'" 
            :pindex="0" 
            :placeholder="'结束地点'" 
            :defList="stationList" 
            :point="fm.ps.spoint"
            :defPoint="fm.ps.epoint"
            @handleSel="setPoint"
            style="width: 265px;"/>
        </el-form-item>

        <el-form-item label="出发时间" required style="margin-bottom: 0px;">
          <div style="display: flex;justify-content: flex-start;">
            <el-form-item 
              prop="sdate"
              :rules="[{ required: true, message: '请选择出发日期', trigger: 'blur' }]">
              <el-date-picker 
                type="date" 
                :value-format="'yyyy-MM-dd'"
                placeholder="选择出发日期" 
                v-model="fm.ps.sdate" 
                :picker-options="sdateOptions"
                @change="sdateOnChange"
                style="width: 135px;margin-right: 10px;">
              </el-date-picker>
            </el-form-item>

            <el-form-item 
              prop="stime"
              :rules="[{ required: true, message: '请选择出发时间', trigger: 'blur' }]">
              <el-time-select
                placeholder="出发时间"
                v-model="fm.ps.stime"
                :picker-options="{
                  start: '00:00',
                  step: '00:10',
                  end: '23:50',
                  minTime: minStime
                }"
                style="width: 120px;">
              </el-time-select>
            </el-form-item>
          </div>
        </el-form-item>

        <el-form-item 
          label="等待时间"
          prop="waitTime"
          :rules="[{ required: true, message: '请选择等待时间', trigger: 'change' }]">
          <el-select 
            v-model="fm.ps.waitTime"
            placeholder="请选择等待时间"
            style="width:265px">
            <el-option
              v-for="it in waitTimeItem"
              :key="it.val"
              :label="it.label"
              :value="it.val">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上车人数" required style="margin-bottom: 0px;">
          <div style="display: flex;justify-content: flex-start;">
            <el-form-item 
              prop="plateNum"
              :rules="[{ required: true, message: '请选择车牌号', trigger: 'change' }]">
              <el-select 
                v-model="fm.ps.plateNum"
                placeholder="请选择车牌号"
                style="width: 155px;margin-right: 10px;">
                <el-option
                  v-for="it in carList"
                  :key="it.val"
                  :label="it.label"
                  :value="it.val"
                  @click.native="onPlateNumChange(it)">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item 
              prop="customers"
              :rules="[
                { required: true, message: '请填写上车人数', trigger: ['blur', 'change'] },
                this.$rules.isPosInt('至少输入1人')
              ]">
              <el-input 
                type="money" 
                v-model.number="fm.ps.customers" 
                placeholder="上车人数" 
                maxlength="6"
                style="width: 100px;"
                @blur="onCustomersBlur">
                <b slot="suffix">人</b>
              </el-input>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button 
          type="primary" 
          :icon="'el-icon-plus'" 
          @click="onSubmit" 
          :loading="fm.sb.load">
          立即发布
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-drag-dialog";

import MapPointInp from '@/components/MapPointInp';

import * as commonSer from '@/api/services/common.service';
import * as orderSer from '@/api/services/order.service';

export default {
  name: 'PubEmptyCar',
  directives: { elDragDialog },
  components: { MapPointInp },
  props: { myData: Object },
  data() {
    return {
      // 出发时间日期-设置
      sdateOptions: {
        disabledDate(time) {
          // 只能选择当前时间之后的时间
          const dd = new Date();
          dd.setDate(dd.getDate() - 1);
          return time < dd;
        }
      },
      // 出发时间-设置
      minStime: '',

      fm: {// 表单数据对象
        fname: "pubEmptyCarFm",
        sb: { load: false },
        ps: {
          // 出发地点
          spoint: {              
            address: '',        // 地址详情 成都市 武侯区 天府广场
            name: '',           // 地址简称 天府广场
            lnglat: '',         // 地点坐标 140.xxxxxx,30.xxxxxx
            isSta: false
          },
          // 到达地点
          epoint: {             
            address: '',        // 地址详情 成都市 武侯区 天府广场
            name: '',           // 地址简称 天府广场
            lnglat: '',         // 地点坐标 140.xxxxxx,30.xxxxxx
            isSta: false
          },
          // 接送类型 0-接 1-送
          isShuttle: 0,
          // 交通类型：1-飞机 2-火车
          travelWay: 0,
          // 出发日期
          sdate: null,
          // 出发时间
          stime: null,
          // 等待时间
          waitTime: null,
          // 车牌号
          plateNum: null,
          // 乘车人数
          customers: null,
        },
      },

      // 修改对象数据
      obj: this.myData.obj,

      // 站点列表
      stationList: [],
      // 等待时间选项列表
      waitTimeItem: [],
      // 车辆选项列表
      carList: [],

    }
  },
  async created() {
    const that = this;

    // 生成等待时间选项数据
    for(let i = 0; i < 24; i++){
      if(i == 0){
        that.waitTimeItem.push({val: 30, label: '30分钟'});
      }else{
        that.waitTimeItem.push({val: i*60, label: `${i}小时`});
      }
    }

    // 设置表单默认数据
    // that.setInitData();

    that.getStationList();
    that.getCarTeamAllPlateNumList();
  },
  methods:{
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    /**
     * 获取-接送机站点列表
     */
    getStationList(){
      const that = this;

      commonSer.getStationList({}).then(res => {
        if(res.code == 1){
          let list = res.data;

          list.forEach(it => {
            that.stationList.push({
              id: it.id,                    // id
              type: it.type,                // 类型 1-飞机 2-火车
              isSta: true,                  // 是否是站点地点
              lnglat: it.mapPoint.lngLat,   // 坐标
              area: it.county,              // 区域
              name: it.name,                // 地点简写
              address: it.mapPoint.address, // 地址
              note: it.nameNote             // 站点别名
            });
          });
        }
      });
    },
    /**
     * 获取-车队所有车牌列表
     */
    getCarTeamAllPlateNumList(){
      const that = this;

      commonSer.getAllCarList({}).then(res => {
        if(res.code == 1){
          let list = res.data;

          that.carList.push({val: '0', label: `自定义`, seats: ''});
          list.forEach(it => {
            that.carList.push({val: it.other, label: `${it.other}（${it.text}座）`, seats: it.text});
          });
        }
      });
    },
    // 设置初始化数据
    setInitData(){
      const that = this;

      // 设置-回填数据
      if(that.obj) {
        let o = that.obj;

        let ps = {
          // 修改对象id
          updId: o.id,
          // 座位数 eg：19
          seats: o.seats+'',
          // 保障用车价格 eg：30
          ensurePrice: o.ensurePrice
        };
        that.fm.ps = ps;
      }
    },
    // 日期选择控制
    sdateOnChange(goDate){
      const that = this, stime = that.fm.ps.stime;
      
      let nowTime = that.$moment();

      // 日期一样，则日期选择的今天
      if(nowTime.format('YYYY-MM-DD') == goDate){
        // 默认设置时间的最小值
        let hhmm = nowTime.format('HH:mm');
        that.minStime = hhmm;
      }else{
        // 不控制时间最小值
        that.minStime = '';
      }

      if(stime){// 存在开始时间
        let goTime = that.$moment(goDate+' '+stime+':00');

        // 出发时间小于当前时间
        if(goTime.isBefore(nowTime)){
          // 则清空时间
          that.fm.ps.stime = '';
        }
      }
    },
    // 选择地点后的回调函数
    setPoint(e){
      let that = this, U = that.U, fm = that.fm, ps = fm.ps;
      console.log('地点子组件传入的数据', e);
      if(e.p){
        ps[e.name] = {
          area: e.p.area, 
          address: e.p.address, 
          name: e.p.name, 
          lnglat: e.p.lnglat, 
          isSta: e.p.isSta,
          type: e.p.type,
          note: e.p.note || ''
        };

        // 对应点不为空，则取消验证
        if(ps[e.name].name) U.clearFmVali(that, fm.fname, `${e.name}.name`);

        // 如果是站点，则赋值交通类型
        if(e.p.isSta) ps.travelWay = e.p.type;
      }else{// 设置地点为空
        ps[e.name] = {
          address: '',
          name: '',
          lnglat: '',
          isSta: false
        };
        
        ps.travelWay = 0;
      }
    },

    // 车牌选择事件
    onPlateNumChange(o){
      const that = this;

      if(o.val){
        if(o.val == 0){
          that.fm.ps.customers = '';
        }else{
          that.fm.ps.customers = parseInt(o.seats) - 1;
        }
      }
    },

    // 上车人数输入框失焦事件
    onCustomersBlur(){
      const that = this, FV = that.FV;

      // 如果用户输入了上车人数，则通过人数去匹配车辆列表中座位数（输入人数+1），如果匹配到对应的座位数，则车牌号对应选中
      if(FV.isInt(that.fm.ps.customers) && parseInt(that.fm.ps.customers) > 0){
        let o = that.carList.find(it => parseInt(it.seats) == (parseInt(that.fm.ps.customers)+1));
        if(o) {
          // 选中对应车牌（如果有一样座位数的车，可能有问题）
          // that.fm.ps.plateNum = o.val;

          // 匹配到对应车牌也叫自定义 2022.5.23
          that.fm.ps.plateNum = '0';
        }else{// 没匹配上，则是自定义
          that.fm.ps.plateNum = '0';
        }
      }
    },

    // 提交表单
    onSubmit() {
      let that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps);
      console.log('初始提交参数', ps);
      that.$refs[fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          sb.load = true;

          // 处理参数
          let p = {};
          // 交通类型
          p.travelWay = ps.travelWay;
          // 出发地点 eg:成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区
          p.spoint = `${ps.spoint.area.split('-')[1]} ${ps.spoint.name}=${ps.spoint.lnglat}=${ps.spoint.area}`;
          // 到达地点 eg:成都市 天府广场=103.666666,30.666666=四川省-成都市-武侯区
          p.epoint = `${ps.epoint.area.split('-')[1]} ${ps.epoint.name}=${ps.epoint.lnglat}=${ps.epoint.area}`;
          // 接送类型 eg:0接 1送
          p.isShuttle = ps.spoint.isSta == true ? 0 : 1;
          // 出发时间 eg:2022-02-02 08:30
          p.stime = `${ps.sdate} ${ps.stime}`;
          // 最晚等待时间（分钟） eg:240
          p.waitTime = ps.waitTime;
          // 车牌号
          p.plateNum = ps.plateNum;
          // 上车人数
          p.customers = ps.customers;
          
          orderSer.addSfcEmptyCar(p).then((res) => {
            sb.load = false;

            if (res.code != 1) {
              U.qerror(res.msg);
            } else {
              U.qsuccess(res.msg);

              // 关闭弹框
              that.closeMd();

              // 调用父组件方法-重新加载数据
              that.$emit("reloadDg");
            }
          });

          setTimeout(() => { sb.load = false; }, 10000);
        }
      });
    },
    
  },
 }
</script>